package com.kiln.juxingqs.ui.vm

import android.app.Application
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.global.commlib.network.data.JsonResult
import client.global.commlib.network.data.Ret
import client.global.commlib.out_time
import client.global.commlib.toast.toast
import client.global.commlib.utils.StoreUtil
import com.kiln.juxingqs.api.bean.GetDddBatchRet
import com.kiln.juxingqs.api.bean.QueryUser
import com.kiln.juxingqs.api.bean.UserInfo
import com.kiln.juxingqs.ui.viewmodel.MiddleVm
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import retrofit2.Response

class ZrxyDddViewModel(val app: Application) : MiddleVm(app) {


    val call = MutableLiveData<JsonResult<Ret>>()
    val queryRet = MutableLiveData<JsonResult<QueryUser>>()
    val isShowing = MutableLiveData<Boolean>()

    val sNum = MutableLiveData<String>("")
    val otherAccount = MutableLiveData<String>("")
    val password = MutableLiveData<String>("")
    val otherName = MutableLiveData<String>("")

    val selectDddBath = MutableLiveData<GetDddBatchRet.Batch>()

    var transfer_price2 = MutableLiveData<String>("")

    val guaMaiWho = MutableLiveData<String>("")
    var serverType: Int? = 0
    var ddd_type: Int? = 0 //点对点类型 1预支点对点

    val serverName = MutableLiveData<String>("")
    val goodsName = MutableLiveData<String>("")

    val f_price = MutableLiveData<String>("")
    var g_price = MutableLiveData<String>("")
    var goodsId = MutableLiveData<String>("")
    var goodsPrice = MutableLiveData<String>("")

    val userInfo = MutableLiveData<UserInfo>().apply {
        value = StoreUtil.getBean<UserInfo>(app)
//        transfer_price2.value = value!!.transfer_price
    }

    /**
     */
    fun ok() {
        when (serverType) {
            1 -> {
                hang(goodsId.value.toString(), goodsPrice.value.toString(), "1")
            }
            12 -> {
                hang(goodsId.value.toString(), goodsPrice.value.toString(), "1")
            }
            122 -> {
                hang(goodsId.value.toString(), goodsPrice.value.toString(), "1")
            }
            2 -> {
                hang(goodsId.value.toString(), goodsPrice.value.toString(), "2")
            }
            0 -> {
                default()
            }

        }

    }

    //r_type=1挂牌服务中心，2挂牌供应商
    fun hang(goodsId: String, goodsPrice: String, r_type: String) {
        if (TextUtils.isEmpty(sNum.value)) {
            toast("请输入交易数量")
            return
        }
        if (TextUtils.isEmpty(password.value)) {
            toast("请输入交易密码")
            return
        }
        isShowing.value = true
        viewModelScope.launch {
            flow {
                var emm: Response<JsonResult<Ret>>? = null
                out_time {
                    val ret = server.validatePayPwd(password.value!!)
                    emm = ret
                }
                emit(emm)
            }.map {
                var emm: Response<JsonResult<Ret>>? = it
                it?.body()?.let {
                    if (it.isSuccess) {
                        out_time {
                            val ret = server.hang_order(
                                goodsId,
                                goodsPrice,
                                sNum.value!!,
                                r_type
                            )
                            emm = ret
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO)
                .onCompletion {
                    isShowing.value = false
                }.catch { cause ->
                    if (cause != null) {
                        toast(cause.message)
                    }
                }.collectLatest {
                    call.value = it?.body()

                }
        }
    }


    private fun default() {
        if (TextUtils.isEmpty(otherAccount.value)) {
            toast("请输入对方账号")
            return
        }
        if (TextUtils.isEmpty(otherName.value)) {
            toast("对方姓名不能为空")
            return
        }
        if (TextUtils.isEmpty(sNum.value)) {
            toast("请输入交易数量")
            return
        }
        if (TextUtils.isEmpty(password.value)) {
            toast("请输入交易密码")
            return
        }

        isShowing.value = true
        viewModelScope.launch {
            flow {
                var emm: Response<JsonResult<Ret>>? = null
                out_time {
                    val ret = server.validatePayPwd(password.value!!)
                    emm = ret
                }
                emit(emm)
            }.map {
                var emm: Response<JsonResult<Ret>>? = it
                it?.body()?.let {
                    if (it.isSuccess) {

                        out_time {
                            if (ddd_type == 2) {//冻结点对点
                                val ret = server.release_transfer(
                                    otherAccount.value!!,
                                    sNum.value!!,
                                    goodsId.value.toString(),
                                    goodsPrice.value.toString(),
                                )
                                emm = ret
                            } else if (ddd_type == 1) {//预支点对点
                                val ret = server.borrow_transfer(
                                    otherAccount.value!!,
                                    sNum.value!!,
                                    goodsId.value.toString(),
                                    goodsPrice.value.toString(),
                                )
                                emm = ret
                            } else { //普通点对点
                                val ret = server.seller_transfer_batch(
                                    otherAccount.value!!,
                                    sNum.value!!,
                                    goodsId.value.toString(),
                                    goodsPrice.value.toString(),
                                )
                                emm = ret
                            }

                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO)
                .onCompletion {
                    isShowing.value = false
                }.catch { cause ->
                    if (cause != null) {
                        toast(cause.message)
                    }
                }.collectLatest {
                    call.value = it?.body()

                }
        }

    }

    fun query() {
        if (otherAccount.value.isNullOrEmpty()) {
            toast("请输入内容")
            return
        }
        hold({
            server.queryUser(otherAccount.value!!)
        }, {
            isShowing.value = true
        }, {
            queryRet.value = it
        }, complete = {
            isShowing.value = false
        })
    }
}